import {defineStore} from "pinia";
import {v4 as uuidv4} from 'uuid';
import {getUserInfo, logout} from "@/api/user";

export const useUserStore = defineStore('user', {
	state(): { uuid_token: string | null, token: string | null, userInfo: any | null, } {
		return {
			// 未登录时的临时token
			uuid_token: null,
			//登录成功后的token
			token: null,
			//用户信息
			userInfo: null,
		}
	},
	getters: {
		uuidToken: (state) => {
			if (!state.uuid_token) {
				state.uuid_token = localStorage.getItem('uuid_token');
			}
			if (!state.uuid_token) {
				state.uuid_token = uuidv4();
				localStorage.setItem('uuid_token', state.uuid_token as string);
			}
			return state.uuid_token;
		},
		userToken: (state) => {
			if (!state.token) {
				state.token = localStorage.getItem('token');
			}
			return state.token;
		},
	},
	actions: {
		saveToken(token: string) {
			this.token = token;
			localStorage.setItem('token', token);
		},
		logout() {
			return logout().then(() => {
				this.token = null;
				this.userInfo = null;
				localStorage.removeItem('token');
			});
		},
		/**
		 * 获取用户信息
		 */

		async getUser() {

			//用户信息已经存在，直接返回
			if (this.userInfo) {
				return this.userInfo;
			}
			//用户没登录，返回
			if (!this.userToken) {
				return this.userInfo;
			}
			//使用token查询用户信息并保存
			const {data} = await getUserInfo();
			this.userInfo = data;
			return this.userInfo;
		},
	}
})
